package com.boruan.shengtangfeng.admin.controller;

import java.util.Date;
import java.util.List;

import com.boruan.shengtangfeng.core.dao.IArticleCategoryDao;
import com.boruan.shengtangfeng.core.dao.IIncorrectQuestionDao;
import com.boruan.shengtangfeng.core.dto.*;
import com.boruan.shengtangfeng.core.dto.mapper.QuestionDtoMapper;
import com.boruan.shengtangfeng.core.entity.*;
import com.boruan.shengtangfeng.core.service.*;
import com.boruan.shengtangfeng.core.vo.*;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.boruan.shengtangfeng.admin.jwt.UserSubject;
import com.boruan.shengtangfeng.admin.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.core.entity.Log.OperateType;
import com.boruan.shengtangfeng.core.enums.Sex;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.utils.StringUtils;
import com.boruan.shengtangfeng.core.utils.UserUtil;
import com.boruan.shengtangfeng.core.vo.mapper.ArticleVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.QuestionVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.VideoVoMapper;

import cn.jpush.api.JPushClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/admin/user")
@Api(value = "", tags = {"NO:7 用户相关接口"})
public class UserApi {
    @Autowired
    private ILogService sysLogService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IVideoService videoService;
    @Autowired
    private JPushClient jPushClient;
    @Autowired
    private IInformService informService;
    @Autowired
    private IIncorrectQuestionDao incorrentQuestionDao;
    @Autowired
    private IArticleCategoryDao articleCategoryDao;


    /**
     * 分页查询用户信息分页数据
     */
    @GetMapping(value = "/page")
    @ApiOperation(value = "NO:7-2 分页查询用户信息", notes = "")
    public GlobalReponse<PageQuery<User>> page(@RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                               User student, Model model) {
//		studentSubject studentSubject=(studentSubject)SecurityUtils.getSubject().getPrincipal();
        PageQuery<User> query = new PageQuery<User>();
        query.setPageNumber(pageIndex);
        query.setPageSize(pageSize);
        userService.pageQuery(query, student);
        return GlobalReponse.success(query);
    }

    @GetMapping(value = "/get")
    @ApiOperation(value = "NO:7-3 查询学生的详细信息，data1返回Sex数组，系统内所有的性别", notes = "")
    public GlobalReponse<User> get(Long id) {
//		studentSubject studentSubject=(studentSubject)SecurityUtils.getSubject().getPrincipal();
        User student = new User();
        if (id != null) {
            student = userService.findById(id);
        }
        GlobalReponse reponse = GlobalReponse.success(student);
        reponse.setData1(Sex.values());
        return reponse;
    }

    @PostMapping(value = "/checkMobile")
    @ApiOperation(value = "NO:7-4 校验手机号是否存在", notes = "")
    public GlobalReponse checkMobile(@RequestParam("mobile") String mobile, @RequestParam("id") Long id) {
        if (id == null) {
            User student1 = userService.findByMobile(mobile);
            if (student1 != null) {
                return GlobalReponse.fail();
            } else {
                return GlobalReponse.success();
            }
        } else {
            User student = userService.findByMobile(mobile);
            if (student == null || student.getId().equals(id)) {
                return GlobalReponse.success();
            } else {
                return GlobalReponse.fail();
            }
        }
    }
    /**
     *
     * 以下接口挪动到了管理员中，并且进行了改动
     */

//	@PostMapping(value = "/add")
//	@ApiOperation(value = "NO:7-5 添加学生", notes = "")
//	public GlobalReponse add(Student student, String plainPassword) {
//		try {
//			UserSubject studentSubject = JwtUtil.getCurrentJwtUser();
//			Log sysLog = new Log();
//			if (student.getId() == null) {
//				// 添加
//				student.setCreateBy(student.getName());
//				student.setCreateTime(new Date());
//				student.setIsDeleted(false);
//				student.setIsLocked(false);
//				userService.save(student, plainPassword);
//				sysLog.setObjectId(student.getId());
//				sysLog.setContent("管理员添加学生信息");
//				sysLog.setOperateType(OperateType.ADD);
//			} else {
//				// 更新
//				Student student2 = userService.findById(student.getId());
//				student2.setName(student.getName());
//				student2.setDepartmentId(student.getDepartmentId());
//				;
//				student2.setDepartmentName(student.getDepartmentName());
//				;
//				student2.setSchoolClassId(student.getSchoolClassId());
//				student2.setSchoolClassName(student.getSchoolClassName());
//				student2.setSpecialityId(student.getSpecialityId());
//				student2.setSpecialityName(student.getSpecialityName());
//				student2.setHeadImage(student.getHeadImage());
//				student2.setSex(student.getSex());
//				student2.setUpdateBy(student.getName());
//				student2.setUpdateTime(new Date());
//				userService.save(student2);
//				sysLog.setObjectId(student2.getId());
//				sysLog.setContent("管理员修改学生信息");
//				sysLog.setOperateType(OperateType.UPDATE);
//			}
//			sysLog.setCreateTime(new Date());
//			sysLog.setOperater(studentSubject.getId());
//			sysLog.setLogType(Log.LogType.ADMIN);
//			sysLogService.save(sysLog);
//			return GlobalReponse.success();
//		} catch (Exception e) {
//			log.error("学生管理保存学生失败:{}", e);
//			return GlobalReponse.fail();
//		}
//	}

    /**
     * 根据id/手机号/昵称查询用户
     */
    @GetMapping(value = "/findByIdTelName")
    @ApiOperation(value = "NO:1-1 根据id，手机号，昵称查询用户", notes = "")
    public GlobalReponse<PageQuery<User>> findByIdTelName(@RequestParam User user) {
        List<User> userList = userService.findByTemplate(user);
        return GlobalReponse.success(userList);
    }

    /**
     * 根据id查询用户
     */
    @GetMapping(value = "/findUserById")
    @ApiOperation(value = "根据id查询用户", notes = "")
    public GlobalReponse<User> findByIdTelName(Long userId) {
        User user = userService.findByIdTelName(userId);
        return GlobalReponse.success(user);
    }

    /**
     * 新增用户
     */
    @PostMapping(value = "/insertUser")
    @CrossOrigin
    @ApiOperation(value = "NO:1-2 新增用户", notes = "")
    public GlobalReponse insertUser(@RequestBody User user) {

        try {
            UserSubject userSubject = JwtUtil.getCurrentJwtUser();
            Log sysLog = new Log();

            if (user.getId() == null) {
                userService.addUser(user);
            } else {
                // 更新
                User old = userService.findById(user.getId());
                if (StringUtils.isNotBlank(user.getPassword())) {
                    old.setSalt(UserUtil.getSalt());
                    old.setPassword(UserUtil.entryptPassword(user.getPassword(), old.getSalt()));
                }
                old.setRemark(user.getRemark());
                old.setUpdateBy(userSubject.getName());
                old.setUpdateTime(new Date());
                userService.save(old);
                sysLog.setObjectId(old.getId());
                sysLog.setContent("管理员修改用户信息");
                sysLog.setOperateType(OperateType.UPDATE);
            }
            sysLog.setCreateTime(new Date());
            sysLog.setOperater(userSubject.getId());
            sysLog.setLogType(Log.LogType.ADMIN);
            sysLogService.save(sysLog);
            return GlobalReponse.success();
        } catch (Exception e) {
            log.error("管理员编辑用户失败:{}", e.getMessage());
            return GlobalReponse.fail(e.getMessage());
        }
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/delete")
    @ApiOperation(value = "NO:1-3 删除用户", notes = "")
    public GlobalReponse delete(@RequestParam("id") Long id) {
        UserSubject studentSubject = JwtUtil.getCurrentJwtUser();
        User student = userService.findById(id);
        student.setIsDeleted(true);
        student.setUpdateBy(studentSubject.getName());
        student.setUpdateTime(new Date());
        try {
            userService.save(student);
            Log sysLog = new Log();
            sysLog.setContent("用户管理删除用户信息");
            sysLog.setCreateTime(new Date());
            sysLog.setOperater(studentSubject.getId());
            sysLog.setObjectId(studentSubject.getId());
            sysLog.setLogType(Log.LogType.ADMIN);
            sysLog.setOperateType(OperateType.DELETE);
            sysLogService.save(sysLog);
            return GlobalReponse.success();
        } catch (Exception e) {
            log.error("用户管理删除用户信息失败:{}", e.getMessage());
            return GlobalReponse.fail();
        }
    }

    /**
     * 封号
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/lock")
    @ApiOperation(value = "NO:1-3 用户封号", notes = "")
    public GlobalReponse lockUser(@RequestParam("id") Long id, @RequestParam("type") Integer type) {
        UserSubject studentSubject = JwtUtil.getCurrentJwtUser();

        try {
            userService.lockUser(id, studentSubject.getId(), type);
            Log sysLog = new Log();
            sysLog.setContent("用户管理删除用户信息");
            sysLog.setCreateTime(new Date());
            sysLog.setOperater(studentSubject.getId());
            sysLog.setObjectId(studentSubject.getId());
            sysLog.setLogType(Log.LogType.ADMIN);
            sysLog.setOperateType(OperateType.DELETE);
            sysLogService.save(sysLog);
            return GlobalReponse.success();
        } catch (Exception e) {
            log.error("用户管理删除用户信息失败:{}", e.getMessage());
            return GlobalReponse.fail();
        }
    }


    @GetMapping("/pageUserComment")
    @ApiOperation(value = "NO:8-16 分页获取评论的文章或者视频，如果返回的视频或者文章为空，则是该文章被删除了", notes = "")
    public GlobalReponse<PageQuery<ArticleVideoCommentVo>> pageUserComment(@RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String userName,
            @RequestParam(required = false) String content
            ) {
        PageQuery<ArticleVideoCommentVo> pageQuery = new PageQuery<ArticleVideoCommentVo>();
        pageQuery.setPageNumber(pageIndex);
        pageQuery.setPara("userId", userId);
        pageQuery.setPara("userName", userName);
        pageQuery.setPara("content", content);
        pageQuery.setPara("status", status);
        pageQuery.setPara("type", type);
        userService.pageComment(pageQuery);
        List<ArticleVideoCommentVo> vos=pageQuery.getList();
        vos.forEach(vo->{
            if (vo.getType()==0) {
                //试题
                Question question=questionService.findById(vo.getObjectId());
                if(!question.getIsDeleted()) {
                    vo.setQuestion(QuestionVoMapper.MAPPER.toVo(question));
                }
            }else if (vo.getType()==1) {
                //文章
                Article article=articleService.findId(vo.getObjectId());
                if(!article.getIsDeleted()) {
                    vo.setArticle(ArticleVoMapper.MAPPER.toVo(article));
                }
            }else if(vo.getType()==2){
                //视频
                Video video=videoService.findId(vo.getObjectId());
                if(!video.getIsDeleted()) {
                    vo.setVideo(VideoVoMapper.MAPPER.toVo(video));
                }
                
            }
        });
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }
    
    @GetMapping(value = "/deleteComments")
    @ApiOperation(value = "NO:8-17 删除用户的评论 type 0 试题 1 文章 2视频", notes = "")
    public GlobalReponse deleteComments(@RequestParam String ids,
                                        @RequestParam Integer type) {

        userService.deleteComments(ids, type);

        return GlobalReponse.success();
    }
    @GetMapping(value = "/updateCommentStatus")
    @ApiOperation(value = "NO:8-17 修改用户的评论 type 0 试题 1 文章 2视频", notes = "")
    public GlobalReponse updateCommentStatus(Long id,Integer type,Integer status) {
        
        userService.updateCommentStatus(id,type,status);
        
        return GlobalReponse.success();
    }


    @GetMapping("/newCheck")
    @ApiOperation(value = "NO:8-18 获取新的待审核评论，文章，视频", notes = "")
    public GlobalReponse<Boolean> newCheck() {
        PageQuery<ArticleVideoCommentVo> pageQuery = new PageQuery<ArticleVideoCommentVo>();
        pageQuery.setPara("status","0");
        userService.pageComment(pageQuery);
        List<ArticleVideoCommentVo> vos=pageQuery.getList();
        //查询待审核用户文章
        Article article = new Article();
        List<Article> articleList = articleService.newCheck(article);

        //查询待审核用户视频
        Video video = new Video();
        List<Video> videoList = videoService.newCheck(video);

        if(!articleList.isEmpty() || !videoList.isEmpty() || !vos.isEmpty()){
            return GlobalReponse.success("有最新审核",1);
        }else{
            return GlobalReponse.success("无最新审核",0);
        }
    }

    @PostMapping("/pageUserArticle")
    @ApiOperation(value = "V4E-001 用户全部文章")
    public GlobalReponse<PageQuery<ArticleVo>> pageUserArticle(@RequestBody ArticlePageSearch articlePageSearch,@RequestParam(value = "userId")Long userId){
        PageQuery<Article> pageQuery = new PageQuery<>();
        pageQuery.setPageSize(articlePageSearch.getPageSize());
        pageQuery.setPageNumber(articlePageSearch.getPageNo());
        if(articlePageSearch.getKeyword()!=null){
            pageQuery.setPara("keyword",articlePageSearch.getKeyword());
        }
        Article article = new Article();
        article.setStatus(articlePageSearch.getStatus());
        article.setCategoryId(articlePageSearch.getCategoryId());
        article.setPublishId(userId);
        articleService.pageQuery(pageQuery,article);
        List<Article> list = pageQuery.getList();
        List<ArticleVo> listVo = ArticleVoMapper.MAPPER.toVo(list);
        for (ArticleVo articleVo : listVo) {
            if (articleVo.getCategoryId()!=null){
                ArticleCategory unique = articleCategoryDao.unique(articleVo.getCategoryId());
                articleVo.setCategoryName(unique.getName());
            }
        }
        pageQuery.setList(listVo);
        return GlobalReponse.success(pageQuery);
    }

    @PostMapping("/pageUserVideo")
    @ApiOperation(value = "V4E-002 查询用户全部视频")
    public GlobalReponse<PageQuery<VideoVo>> pageUserVideo(@RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
                                                           @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                                           Video video){
        PageQuery<Video> pageQuery = new PageQuery<Video>();
        pageQuery.setPageNumber(pageIndex);
        pageQuery.setPageSize(pageSize);
        video.setIsDeleted(false);
        videoService.pageQuery(pageQuery, video);
        List<Video> list = pageQuery.getList();
        List<VideoVo> vos = VideoVoMapper.MAPPER.toVo(list);
        pageQuery.setList(vos);
        return GlobalReponse.success(pageQuery);
    }

    @PostMapping("/pageUserInQuestion")
    @ApiOperation(value = "V4E-003 查询用户全部错题")
    public GlobalReponse<PageQuery<IncorrectQuestion>> pageUserInQuestion(@RequestBody IncorrentQuestionListDto incorrentQuestionListDto,@RequestParam(value = "userId")Long userId){

        //实例化分页类
        PageQuery<IncorrectQuestion> pageQuery = new PageQuery<IncorrectQuestion>();
        pageQuery.setPageNumber(incorrentQuestionListDto.getPageNo());//设置分页
        pageQuery.setPageSize(incorrentQuestionListDto.getPageSize());
        pageQuery.setParas(incorrentQuestionListDto);
        pageQuery.setPara("userId",userId);
        questionService.getSelfUpQuestion(pageQuery);
        return GlobalReponse.success(pageQuery);
    }

    @CrossOrigin
    @PostMapping(value = "/pageUserQuestions")
    @ApiOperation(value = "V4E-004 查看用户全部试题", notes = "")
    public GlobalReponse<PageQuery<QuestionVo>> pageUserQuestions(@RequestParam(value = "status",required = false)@ApiParam(value = "状态0待审核1通过2拒绝")Integer status,
                                                 @RequestParam(value = "userId") Long userId,
                                                 @RequestParam(value = "keywords",required = false)String keywords,
                                                 @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                                 @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        PageQuery<Question> pageData = new PageQuery<Question>();
        pageData.setPageNumber(pageNo);
        pageData.setPageSize(pageSize);
        Question question = new Question();
        question.setTitle(keywords);
        question.setStatus(status);
        question.setCreateBy(userId.toString());
        questionService.pageQuery(pageData, question);
        List<QuestionVo> resultList = QuestionVoMapper.MAPPER.toVo(pageData.getList());
        pageData.setList(resultList);
        return GlobalReponse.success(pageData);
    }


    @PostMapping("/pageUserInform")
    @ApiOperation(value = "V4E-005 查看用户全部通知")
    public GlobalReponse<PageQuery<Inform>> pageUserInform(@RequestBody InformDto informDto, @ApiParam(value = "页码")@RequestParam(value = "pageNo",defaultValue = "1")Integer pageNo, @ApiParam(value = "每页数量")@RequestParam(value = "pageSize")Integer pageSize){
        PageQuery<Inform> pageQuery = new PageQuery<>();
        pageQuery.setPageSize(pageSize);
        pageQuery.setPageNumber(pageNo);
        Inform inform = new Inform();
        inform.setCreateBy(informDto.getCreateId().toString());
        inform.setStatus(informDto.getStatus());
        inform.setContent(informDto.getContent());
        informService.pageQuery(pageQuery,inform);
        return GlobalReponse.success(pageQuery);
    }


    @PostMapping("/pageUserQuestionRecord")
    @ApiOperation(value = "V4E-006 查看用户全部答题")
    public GlobalReponse<PageQuery<QuestionRecordVo>> pageUserQuestionRecord(@ApiParam(value = "页码")@RequestParam(value = "pageNo",defaultValue = "1")Integer pageNo, @ApiParam(value = "每页数量")@RequestParam(value = "pageSize")Integer pageSize,@ApiParam(value = "用户ID")@RequestParam(value = "userId")Long userId,@ApiParam(value = "状态：0待审核1通过2拒绝")@RequestParam(value = "status",required = false)Integer status){
        PageQuery<QuestionRecord> pageQuery = new PageQuery<>();
        pageQuery.setPageSize(pageSize);
        pageQuery.setPageNumber(pageNo);
        QuestionRecord search = new QuestionRecord();
        search.setUserId(userId);
        search.setStatus(status);
        questionService.pageQuestionRecord(pageQuery,search);
        return GlobalReponse.success(pageQuery);
    }


    @PostMapping("/pageUserVideoGrade")
    @ApiOperation(value = "V4E-007 查看用户全部点评")
    public GlobalReponse<PageQuery<VideoGrade>> pageUserVideoGrade(@ApiParam(value = "页码")@RequestParam(value = "pageNo",defaultValue = "1")Integer pageNo,
                                                                   @ApiParam(value = "每页数量")@RequestParam(value = "pageSize")Integer pageSize,
                                                                   @ApiParam(value = "用户ID")@RequestParam(value = "userId")Long userId,
                                                                   @ApiParam(value = "关键词")@RequestParam(value = "keywords")String keywords){
        PageQuery<VideoGrade> pageQuery = new PageQuery<>();
        pageQuery.setPageNumber(pageNo);
        pageQuery.setPageSize(pageSize);
        if(userId!=null){
            pageQuery.setPara("userId",userId);
        }
        if(StringUtils.isNotBlank(keywords)){
            pageQuery.setPara("remark",keywords);
        }
        videoService.pageVideoGrade(pageQuery);
        return GlobalReponse.success(pageQuery);
    }

    @PostMapping("/selfQuestion")
    @ApiOperation(value = "V4D-01 待审核的错题列表")
    public GlobalReponse<PageQuery<IncorrectQuestion>> selfQuestion(@RequestBody IncorrentQuestionListDto incorrentQuestionListDto){
        //实例化分页类
        PageQuery<IncorrectQuestion> pageQuery = new PageQuery<IncorrectQuestion>();
        pageQuery.setPageNumber(incorrentQuestionListDto.getPageNo());//设置分页
        pageQuery.setPageSize(incorrentQuestionListDto.getPageSize());//设置分页

        pageQuery.setPara("startTime",incorrentQuestionListDto.getStartTime());
        pageQuery.setPara("endTime",incorrentQuestionListDto.getEndTime());
        pageQuery.setPara("status",incorrentQuestionListDto.getStatus());
        pageQuery.setPara("keywords",incorrentQuestionListDto.getKeywords());
        pageQuery.setPara("user",incorrentQuestionListDto.getUser());

        questionService.auditSelfQuestion(pageQuery);
        List<IncorrectQuestion> list = pageQuery.getList();
        for (IncorrectQuestion v : list) {
            User user = userService.findById(v.getUserId());
            v.set("user",user);
        }
        pageQuery.setList(list);
        return GlobalReponse.success(pageQuery);
    }

    @PostMapping("/confirmSelfQuestion")
    @ApiOperation(value = "V4D-02 审核错题集")
    public GlobalReponse confirmSelfQuestion(@ApiParam(value = "错题集Id") @RequestParam(value = "inQuestionId") Long inQuestionId, @ApiParam(value = "1通过；2失败")@RequestParam(value = "status") int status){
        UserSubject userSubject= JwtUtil.getCurrentJwtUser();
        IncorrectQuestion incorrectQuestion = questionService.findInQuestion(inQuestionId);
        incorrectQuestion.setStatus(status);
        questionService.auditInQuestion(incorrectQuestion);
        return GlobalReponse.success("审核成功");
    }

    @GetMapping("/delIncorrectQuestion")
    @ApiOperation(value = "V4D-03 删除错题")
    public GlobalReponse delIncorrectQuestion(@RequestParam(value = "incorrectId")String incorrectId){
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        for (String id : incorrectId.split(",")) {
            IncorrectQuestion incorrectQuestion = questionService.findInQuestion(Long.valueOf(id).longValue());
            incorrectQuestion.setIsDeleted(true);
            incorrentQuestionDao.updateById(incorrectQuestion);
        }
        return GlobalReponse.success("删除成功");
    }

    @GetMapping("/giveUserFans")
    @ApiOperation(value = "赠送用户粉丝")
    public GlobalReponse giveUserFans(@RequestParam(value = "userId")Long userId,@RequestParam(value = "fansNum")Integer fansNum){
        Long adminId = JwtUtil.getCurrentJwtUser().getId();
        return userService.giveUserFans(userId,fansNum,adminId);
    }
}
